<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:order:soAdvanceOrder:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor
          v-model:value="model[field]"
          :bizKey="record.id"
          :bizType="'testDataChild_' + field"
          :height="300"
        />
      </template>
      <template #rdsSelect1>
        <ListSelect
          v-model:value="itemCodes"
          :labelValue="itemNames"
          selectType="basInvSelect-orderback"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template>
      <template #testDataChildList>
        <BasicTable
          @register="registerTestDataChildTable"
          @row-click="handleTestDataChildRowClick"
          @edit-change="rowChange"
        >
        </BasicTable>
        <a-button
          class="mt-2"
          @click="handleTestDataChildAdd"
          v-auth="'shop:order:soAdvanceOrder:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增存货') }}
        </a-button>

        <a-button class="mt-2 ml-2" @click="handleTcb" v-auth="'shop:order:soAdvanceOrder:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('选择套餐包') }}
        </a-button>

        <a-button class="mt-2 ml-2" @click="handleZp" v-auth="'shop:order:soAdvanceOrder:edit'">
          <Icon icon="simple-line-icons:menu" /> {{ t('批量修改是否赠品') }}
        </a-button>
      </template>
    </BasicForm>
    <!--  @success="handleSuccess" -->
    <InputFormSubmit @register="registerDrawer3" @success="handleSuccess" />
    <xqform @register="registerxqDrawer" @success="handlexqform" />

    <!-- 选择套餐包 -->
    <BasicModal v-bind="$attrs" @register="registerModal" title="选择套餐包" @ok="handleModal">
      <BasicForm @register="registertcbForm" />
    </BasicModal>

    <!-- 批量修改是否赠品 -->
    <BasicModal v-bind="$attrs" @register="registerModalZp" title="是否赠品" @ok="handleModalZp">
      <BasicForm @register="registerFormZp" />
    </BasicModal>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';

  import { WangEditor } from '/@/components/WangEditor';
  import InputFormSubmit from './form-submit.vue';
  import { ListSelect } from '/@/components/ListSelect';
  import { BasicModal, useModal } from '/@/components/Modal';
  import {
    SoAdvanceOrder,
    soAdvanceOrderSave,
    soAdvanceOrderForm,
  } from '/@/api/shop/order/soAdvanceOrder';
  import { shopSalesPackageTreeData } from '/@/api/shop/sales/shopSalesPackage';

  import xqform from '/@/views/shop/sales/shopSalesPackage/xqform.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.order.soAdvanceOrder');
  const { showMessage } = useMessage();
  const record = ref<any>({} as any);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增销售预订单') : t('编辑销售预订单'),
  }));
  const itemCodes = ref('');
  const itemNames = ref('');
  let queryParams = ref({});
  let listSelectRef = ref([]);

  let soAdvanceOrderChildList = ref([]);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('单号'),
      field: 'code',
      dynamicDisabled: true,
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
    },
    {
      label: t('客户编码'),
      field: 'cusCode',
      dynamicDisabled: true,
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('客户名称'),
      field: 'basCus.name',
      dynamicDisabled: true,
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
      colProps: { lg: 12, md: 24 },
    },
    // {
    //   label: t('存货'),
    //   field: 'invCode',
    //   fieldLabel: 'invName',
    //   component: 'ListSelect',
    //   componentProps: {
    //     selectType: 'basInvSelect-orderback',
    //     checkbox: true,
    //     params: {
    //       cusCode: record.value.cusCode,
    //     },

    //     onSelect(e) {
    //       let flag = true;
    //       let croute = e[0].croute;
    //       e.forEach((item) => {
    //         item.isNewRecord = true
    //         item.basInv = {
    //           'cinvname':item.cinvname,
    //           'unitName':item.unitName
    //         }
    //         // item.basInv.cinvname = item.cinvname
    //         // item.basInv.unitName = item.unitName
    //         if (item.croute != croute) {
    //           flag = false;
    //         }
    //       });
    //       record.value.soAdvanceOrderChildList.forEach(item1=>{
    //         item1.isNewRecord = false
    //         item1.status = '1'
    //       })
    //       if (!flag) {
    //         showMessage(t('请选择相同的协同路线！'));
    //         setFieldsValue({
    //           // ...record.value,
    //           ...getFieldsValue(),
    //           croute: e[0].croute,
    //           basInv: {
    //             cinvcode: '',
    //             cinvName: '',
    //           },
    //         });
    //       } else {
    //         setFieldsValue({
    //           // ...record.value,
    //           ...getFieldsValue(),
    //           croute: e[0].croute,
    //         });
    //         testDataChildTable.setTableData(e || []);
    //       }
    //       console.log(e);
    //     },
    //   },
    //   required: true,
    //   colProps: { lg: 24, md: 24 },
    // },
    {
      label: t('是否预订单'),
      field: 'badvorder',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        allowClear: true,
        onChange: (v) => {
          console.log(v);
          if (v == '1') {
            updateSchema([
              {
                field: 'bbook',
                required: true,
              },
            ]);
          } else {
            updateSchema([
              {
                field: 'bbook',
                required: false,
              },
            ]);
          }
        },
      },
      required: true,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('是否有承诺书'),
      field: 'bbook',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        allowClear: true,
      },
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('协同路线'),
      field: 'croute',
      dynamicDisabled: true,
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('协同描述'),
      field: 'routeDesc',
      dynamicDisabled: true,
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      required: true,
      colProps: { lg: 12, md: 24 },
    },

    {
      label: t('存货'),
      field: 'selIds1',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdsSelect1',
      show: false,
    },

    {
      label: t('商品'),
      field: 'testDataChildList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'testDataChildList',
    },
  ];

  const [registertcbForm, { resetFields: resetFieldstcb, validate: validatetcb }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t('套餐包'),
        field: 'salescode',
        fieldLabel: 'salesname',
        component: 'TreeSelect',
        componentProps: {
          api: shopSalesPackageTreeData,
          allowClear: true,
          // immediate: true,
          // onChange: async(id)=>{
          //   console.log(soAdvanceOrderChildList.value,'soAdvanceOrderChildList.value==');
          //   await testDataChildTable.setTableData([])
          //   if(id){
          //     openxqDrawer(true, {id,showFooter:true});
          //   }
          // }
        },
        required: true,
        itemProps: { validateTrigger: 'blur' },
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [
    registerForm,
    { resetFields, setFieldsValue, getFieldsValue, validate, setProps, updateSchema },
  ] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerTestDataChildTable, testDataChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleTestDataChildDelete.bind(this, record),
          },
          auth: 'shop:order:soAdvanceOrder:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });
  /**
   * 选择
   * @param selectData
   */
  function handSelect(selectData) {
    if (getFieldsValue().croute) {
      let flag = true;
      // let croute = selectData[0].croute;
      let croute = getFieldsValue().croute;
      selectData.forEach((item) => {
        if (item.croute != croute) {
          flag = false;
        }
      });
      if (!flag) {
        showMessage(t('请选择相同的协同路线！'));
      } else {
        console.log(testDataChildTable.getDataSource(), '子表信息-----');

        selectData.forEach((item) => {
          let flag = true;
          // testDataChildTable.getDataSource().forEach((res) => {
          //   if (res.cinvcode == item.cinvcode) {
          //     flag = false;
          //   }
          // });
          if (flag) {
            testDataChildTable.insertTableDataRecord({
              ...item,
              id: '',
              editable: true,
              isNewRecord: true,
              // fretailprice: item.appPrice,
              bgift: '0',
              oldPrice: item.appPrice,
              basInv: {
                cinvname: item.cinvname,
                ichangrate: item.ichangrate,
                unitName: item.unitName,
              },
              ichangerate: item.ichangrate,
            });
          }
        });
      }
    } else {
      console.log(testDataChildTable.getDataSource(), '子表信息-----');
      setFieldsValue({
        ...getFieldsValue(),
        croute: selectData[0].croute,
        routeDesc: selectData[0].routeDesc,
      });
      selectData.forEach((item) => {
        testDataChildTable.insertTableDataRecord({
          id: '',
          editable: true,
          ...item,
          isNewRecord: true,
          // fretailprice: item.appPrice,
          bgift: '0',
          oldPrice: item.appPrice,
          basInv: {
            cinvname: item.cinvname,
            ichangrate: item.ichangrate,
            unitName: item.unitName,
          },
          ichangerate: item.ichangrate,
        });
      });
    }

    // if (selectType.value === 'flowSelect') {
    // selectData.forEach((item) => {
    //   testDataChildTable.insertTableDataRecord({
    //     id: '',
    //     editable: true,
    //     ...item,
    //     isNewRecord: true,
    //     // iqty: item.iqty - (item.fcQty || 0),
    //   });
    // });
    // } else {
    //   m8OrderFlowWxOutRdsTable.insertTableDataRecord({
    //     id: new Date().getTime(),
    //     isNewRecord: true,
    //     editable: true,
    //   });
    // }
  }

  async function setTestDataChildTableData(_res: Recordable) {
    testDataChildTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
        // editable: true,
        // edit: true,
        // editRow: true,
        // editComponent: 'ListSelect',
        // editComponentProps: {
        //   selectType: 'basInvSelect-orderback'
        // },
        // editRule: true,
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 240,
        align: 'left',
      },

      // {
      //   title: t('协同路线'),
      //   dataIndex: 'croute',
      //   width: 120,
      //   align: 'center',
      // },
      // {
      //   title: t('协同描述'),
      //   dataIndex: 'routeDesc',
      //   width: 120,
      //   align: 'center',
      // },

      // {
      //   title: t('单位'),
      //   dataIndex: 'basInv.unitName',
      //   width: 80,
      //   align: 'center',
      // },
      {
        title: t('换算率'),
        // dataIndex: 'basInv.ichangrate',
        dataIndex: 'ichangerate',
        width: 80,
        align: 'center',
      },
      // {
      //   title: t('单价'),
      //   dataIndex: 'appPrice',
      //   align: 'center',
      //   width: 80,
      // },
      {
        title: t('单价'),
        dataIndex: 'appPrice',
        align: 'center',
        width: 80,
      },

      {
        title: t('总价'),
        dataIndex: 'isum',
        align: 'center',
        width: 80,
      },
      {
        title: t('数量'),
        dataIndex: 'iquantity',
        width: 130,
        align: 'center',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'InputNumber',
        editRule: true,
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.unitName',
        width: 60,
        align: 'center',
      },
      {
        title: t('件数'),
        dataIndex: 'inum',
        width: 130,
        align: 'center',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'InputNumber',
        editRule: true,
      },
      {
        title: t('是否赠品'),
        dataIndex: 'bgift',
        width: 130,
        align: 'center',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_yes_no',
        },
        editRule: true,
        dictType: 'sys_yes_no',
      },
    ]);
    // testDataChildTable.setTableData(record.value.testDataChildList || []);
    testDataChildTable.setTableData(_res.soAdvanceOrderChildList || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function rowChange({ column, value, record }) {
    if (column.dataIndex == 'iquantity') {
      record.inum = (value / record.ichangerate).toFixed(4);
      record.isum = (value * record.appPrice).toFixed(2);
    }
    if (column.dataIndex == 'inum') {
      // record.iquantity = value * record.ichangerate;
      record.iquantity = Math.round(value * record.ichangerate);
      record.isum = (record.appPrice * record.iquantity).toFixed(2);
      record.inum = (record.iquantity / record.ichangerate).toFixed(4);
    }
    if (column.dataIndex == 'bgift') {
      if (value == '1') {
        record.appPrice = 0;
        record.isum = 0;
      } else {
        record.appPrice = record.oldPrice;
        record.isum = (record.appPrice * record.iquantity).toFixed(2);
      }
    }
  }

  async function handleTestDataChildAdd() {
    listSelectRef.value = [];
    document.getElementById('form_item_selIds1')?.click();
  }

  function handleTestDataChildDelete(record: Recordable) {
    testDataChildTable.deleteTableDataRecord(record);
    if (testDataChildTable.getDataSource().length == 0) {
      setFieldsValue({
        ...getFieldsValue(),
        croute: '',
        routeDesc: '',
      });
    }
  }

  async function getTestDataChildList() {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];

    for (const record of testDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of testDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      testDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!testDataChildListValid) {
      throw { errorFields: [{ name: ['testDataChildList'] }] };
    }
    return testDataChildList;
  }
  const [registerFormZp, { resetFields: resetFieldsZp, validate: validateZp }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t(''),
        field: 'bgift',
        component: 'Select',
        componentProps: {
          dictType: 'sys_yes_no',
          allowClear: true,
        },
        required: true,
        colProps: { lg: 24, md: 24 },
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerModalZp, { openModal: openModalZp, closeModal: closeModalZp }] = useModal();
  const [registerxqDrawer, { openDrawer: openxqDrawer }] = useDrawer();
  const [registerDrawer3, { openDrawer: openDrawer3 }] = useDrawer();
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await soAdvanceOrderForm({ code: data.code });
    record.value = (res.soAdvanceOrder || {}) as SoAdvanceOrder;
    record.value = {
      ...data,
      ...record.value,
    };
    // record.value = data;
    record.value.__t = new Date().getTime();
    setDrawerProps({ showOkBtn: record.value.settleStatus == '1' ? false : true });
    // record.value.isNewRecord = false;
    queryParams.value = {
      cusCode: record.value.cusCode,
    };
    setFieldsValue(record.value);

    soAdvanceOrderChildList.value = [...res.soAdvanceOrder.soAdvanceOrderChildList];
    setTestDataChildTableData(record.value);
    // setTimeout(() => {
    //   setTestDataChildTableData(record.value);
    // }, 500);
    setDrawerProps({ loading: false });
  });

  function handleSuccess() {
    closeDrawer();
    emit('success', '');
  }

  // 是否赠品
  async function handleZp() {
    await openModalZp(true, {});
    resetFieldsZp();
  }

  async function handleModalZp() {
    let data = await validateZp();
    for (const record of testDataChildTable.getDataSource()) {
      record.bgift = data.bgift;
      record.editValueRefs.bgift = data.bgift;

      if (record.bgift == '1') {
        record.appPrice = 0;
        record.isum = 0;
      } else {
        record.appPrice = record.oldPrice;
        record.isum = (record.appPrice * record.editValueRefs.iquantity).toFixed(2);
      }
    }
    closeModalZp();
  }

  // 套餐包
  async function handleTcb() {
    await openModal(true, {});
    resetFieldstcb();
  }

  async function handleModal() {
    let data = await validatetcb();
    openxqDrawer(true, { id: data.salescode, cusCode: record.value.cusCode, showFooter: true });
    closeModal();
  }

  function handlexqform(res) {
    let selectData = res.list;
    if (getFieldsValue().croute) {
      let flag = true;
      let croute = res.routeVO.route;
      if (getFieldsValue().croute != croute) {
        flag = false;
      }
      if (!flag) {
        showMessage(t('请选择相同的协同路线！'));
      } else {
        console.log(testDataChildTable.getDataSource(), '子表信息-----');

        selectData.forEach((item) => {
          testDataChildTable.insertTableDataRecord({
            id: '',
            editable: true,
            ...item,
            isNewRecord: true,
            // fretailprice: item.appPrice,
            // bgift:'0',
            oldPrice: item.basInv.appPrice,
            appPrice: item.basInv.appPrice,
            // isum: isum,
            cinvcode: item.basInv.cinvcode,
            // basInv: {
            //   cinvname: item.cinvname,
            //   ichangrate: item.ichangrate,
            // },
            inum: item.iqty,
            // iquantity: iquantity,
            ichangerate: item.basInv.ichangrate ? item.basInv.ichangrate : 1,
          });
        });
      }
    } else {
      console.log(testDataChildTable.getDataSource(), '子表信息-----');
      setFieldsValue({
        ...getFieldsValue(),
        croute: res.routeVO.route,
        routeDesc: res.routeVO.routeDesc,
      });
      selectData.forEach((item) => {
        testDataChildTable.insertTableDataRecord({
          id: '',
          editable: true,
          ...item,
          isNewRecord: true,
          // fretailprice: item.appPrice,
          // bgift:'0',
          oldPrice: item.basInv.appPrice,
          appPrice: item.basInv.appPrice,
          // isum: isum,
          cinvcode: item.basInv.cinvcode,
          // basInv: {
          //   cinvname: item.cinvname,
          //   ichangrate: item.ichangrate,
          // },
          inum: item.iqty,
          // iquantity: iquantity,
          ichangerate: item.basInv.ichangrate ? item.basInv.ichangrate : 1,
        });
      });
    }

    // list.forEach((item) => {
    //   let inum = (item.iqty / item.basInv.ichangrate).toFixed(4)
    //     testDataChildTable.insertTableDataRecord({
    //       id: '',
    //       editable: true,
    //       ...item,
    //       isNewRecord: true,
    //       // fretailprice: item.appPrice,
    //       // bgift:'0',
    //       oldPrice:item.iprice,
    //       appPrice:item.iprice,
    //       cinvcode:item.basInv.cinvcode,
    //       // basInv: {
    //       //   cinvname: item.cinvname,
    //       //   ichangrate: item.ichangrate,
    //       // },
    //       inum:inum,
    //       iquantity:item.iqty,
    //       ichangerate: item.basInv.ichangrate
    //     });
    //   });
  }

  async function handleSubmit() {
    try {
      const data = await validate();

      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        soCode: record.value.code,
      };
      data.soAdvanceOrderChildList = await getTestDataChildList();
      console.log('submit', params, data, record);
      const res = await soAdvanceOrderSave(params, data);
      showMessage(res.message);
      // openDrawer3(true, data);
      // setFieldsValue(data);
      // setTestDataChildTableData(data);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
